package com.zzyl.nursing.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.druid.support.json.JSONUtils;
import com.aliyun.iot20180120.Client;
import com.aliyun.iot20180120.models.*;
import com.baomidou.mybatisplus.core.toolkit.BeanUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.framework.config.IotClientConfig;
import com.zzyl.framework.config.properties.AliIoTConfigProperties;
import com.zzyl.nursing.controller.ContractController;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.vo.DeviceVo;
import com.zzyl.nursing.vo.ProductVo;
import org.hibernate.validator.internal.util.Contracts;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 设备表Service业务层处理
 *
 * @author Tomorrow
 * @date 2025-01-10
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService {
    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private IotClientConfig iotClientConfig;

    @Autowired
    private Client client;

    @Autowired
    private AliIoTConfigProperties aliIoTConfigProperties;


    /**
     * 查询设备表
     *
     * @param id 设备表主键
     * @return 设备表
     */
    @Override
    public Device selectDeviceById(Long id) {
        return deviceMapper.selectById(id);
    }

    /**
     * 查询设备表列表
     *
     * @param device 设备表
     * @return 设备表
     */
    @Override
    public List<Device> selectDeviceList(Device device) {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备表
     *
     * @param device 设备表
     * @return 结果
     */
    @Override
    public int insertDevice(Device device) {
        return deviceMapper.insert(device);
    }

    /**
     * 修改设备表
     *
     * @param device 设备表
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateDevice(Device device) {

        //更新数据库中的设备信息
        int result = deviceMapper.updateById(device);

        //更新IOT平台上的设备信息
        BatchUpdateDeviceNicknameRequest request = new BatchUpdateDeviceNicknameRequest();

        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        List<BatchUpdateDeviceNicknameRequest.BatchUpdateDeviceNicknameRequestDeviceNicknameInfo> nicknameInfos = new ArrayList<>();

        BatchUpdateDeviceNicknameRequest.BatchUpdateDeviceNicknameRequestDeviceNicknameInfo nicknameInfo = new BatchUpdateDeviceNicknameRequest.BatchUpdateDeviceNicknameRequestDeviceNicknameInfo();
        nicknameInfo.setNickname(device.getNickname());
        nicknameInfo.setProductKey(device.getProductKey());
        nicknameInfo.setDeviceName(device.getDeviceName());

        nicknameInfos.add(nicknameInfo);

        request.setDeviceNicknameInfo(nicknameInfos);

        BatchUpdateDeviceNicknameResponse response;
        try {
            response = client.batchUpdateDeviceNickname(request);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        if (!response.body.success) {

            throw new BaseException("更新设备失败");
        }


        return result;

    }

    /**
     * 批量删除设备表
     *
     * @param ids 需要删除的设备表主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids) {
        return deviceMapper.deleteBatchIds(Arrays.asList(ids));
    }


    /**
     * 删除设备表信息
     *
     * @param id 设备表主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id) {
        return deviceMapper.deleteById(id);
    }

    /**
     * 从物联网平台同步产品列表
     *
     * @return
     */
    @Override
    public void queryProducList() {

        //创建对象，用来调用方法
        QueryProductListRequest request = new QueryProductListRequest();
        request.setPageSize(100);
        request.setCurrentPage(1);
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());

        //调用阿里云Iot接口查询产品列表数据
        QueryProductListResponse response;
        try {
            response = client.queryProductList(request);
        } catch (Exception e) {
            throw new BaseException("物联网接口-查询产品，同步失败");
        }

        //判断查询结果是否为空
        List<QueryProductListResponseBody.QueryProductListResponseBodyDataListProductInfo> productInfo = response.body.data.list.productInfo;
        if (ObjectUtil.isEmpty(productInfo)) {

            throw new BaseException("物联网接口-查询产品，同步失败");

        }

        //查询成功，存入redis中
        redisTemplate.opsForValue().set(CacheConstants.IOT_PRODUCT_LIST_ALL, JSONUtil.toJsonPrettyStr(productInfo));

    }

    /**
     * 查询所有产品列表
     *
     * @return
     */
    @Override
    public List<ProductVo> allProduct() {


        //从redis中查询查询所有产品列表
        String productList = (String) redisTemplate.opsForValue().get(CacheConstants.IOT_PRODUCT_LIST_ALL);

        List<ProductVo> list = JSONUtil.toList(productList, ProductVo.class);

        //返回数据

        return list;
    }


    /**
     * 新增产品设备
     *
     * @param deviceDto
     */
    @Override
    public void registerDevice(DeviceDto deviceDto) {


        //查询数据库，判断设备名称是否重复
        Long count = deviceMapper.selectCount(Wrappers.lambdaQuery(Device.class).eq(Device::getDeviceName, deviceDto.getDeviceName()));

        //若重复，直接抛异常结束
        if (count > 0) {
            throw new BaseException("设备名称已存在，请重新输入");
        }

        //不重复,新增设备到iot平台
        //获取到iot平台需要的数据
        RegisterDeviceRequest registerDeviceRequest = deviceDto.getRegisterDeviceRequest();

        //获取配置文件中的设备Id
        registerDeviceRequest.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());

        //保存
        RegisterDeviceResponse response;
        try {
            response = client.registerDevice(registerDeviceRequest);
        } catch (Exception e) {
            throw new BaseException("调用物联网接口失败，未注册成功");
        }


        //判断保存设备到IOT是否新增成功
        if (!response.body.success) {
            throw new BaseException("调用IOT平台注册设备失败");

        }

        //注册成功，判断位置类型是否为0,若为0，设置设备物理外键为-1
        if (deviceDto.getLocationType() == 0) {
            deviceDto.setPhysicalLocationType(-1);
        }

        //补全新增时返回的iotId到设备对象中
        String iotId = response.body.data.getIotId();

        //对象属性拷贝
        Device device = BeanUtil.toBean(deviceDto, Device.class);
        device.setIotId(iotId);

        try {
            //保存设备到数据库
            int result = deviceMapper.insert(device);

            //判断设备是否成功保存到数据库
            if (result == 0) {

                //表中的唯一约束导致添加不成功，要删除IOT中的设备
                deleteIOTDevice(deviceDto, iotId);
                throw new BaseException("该老人/位置已绑定该产品，请重新选择");

            }

        } catch (Exception e) {

            //两种情况，设备没有成功保存到数据库，直接失败，要删除IOT中的设备
            deleteIOTDevice(deviceDto, iotId);
            throw new BaseException("该老人/位置已绑定该产品，请重新选择");
        }


    }


    /**
     * 查询产品设备详情
     *
     * @param deviceDto
     * @param iotId
     */
    private void deleteIOTDevice(DeviceDto deviceDto, String iotId) {

        //创建对象
        DeleteDeviceRequest deleteDeviceRequest = new DeleteDeviceRequest();

        //设置需要的数据
        deleteDeviceRequest.setDeviceName(deviceDto.getDeviceName());
        deleteDeviceRequest.setProductKey(deviceDto.getProductKey());
        deleteDeviceRequest.setIotId(iotId);
        deleteDeviceRequest.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());

        try {
            client.deleteDevice(deleteDeviceRequest);
        } catch (Exception e) {
            throw new RuntimeException("调用IOT平台删除设备失败");
        }
    }


    /**
     * 查询产品设备详情
     *
     * @param deviceDto
     * @return
     */
    @Override
    public DeviceVo getDeviceInfo(DeviceDto deviceDto) {

        //1.查询Iot平台，获取数据
        //创建对象
        QueryDeviceDetailRequest request = new QueryDeviceDetailRequest();
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        request.setIotId(deviceDto.getIotId());
        request.setProductKey(deviceDto.getProductKey());

        QueryDeviceDetailResponse response;
        try {
            response = client.queryDeviceDetail(request);
        } catch (Exception e) {
            throw new BaseException("调用IOT平台查询设备详情失败");
        }

        //获取出结果中的设备信息并将结果拷贝到设备详情对象中
        DeviceVo deviceVo = BeanUtil.toBean(response.body.getData(), DeviceVo.class);

        //查询数据库获取基本信息
        Device device = deviceMapper.selectOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, deviceDto.getIotId()));

        //合并，返回数据
        BeanUtil.copyProperties(device, deviceVo);
        return deviceVo;
    }

    /**
     * 查看指定产品的已发布物模型中的功能定义详情
     *
     * @param request
     * @return
     */
    @Override
    public AjaxResult queryThingModelPublished(QueryThingModelPublishedRequest request) {

        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());

        QueryThingModelPublishedResponse response;
        try {
            response = client.queryThingModelPublished(request);
        } catch (Exception e) {
            throw new BaseException("查询物模型数据信息失败");
        }

        if (!response.body.success) {
            throw new BaseException("查询物模型数据信息失败");
        }

        return AjaxResult.success(response.body.data);

    }

    /**
     * 查询指定设备的物模型运行状态
     *
     * @param request
     * @return
     */
    @Override
    public AjaxResult queryDevicePropertyStatus(QueryDevicePropertyStatusRequest request) {

        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());

        QueryDevicePropertyStatusResponse response;
        try {
            response = client.queryDevicePropertyStatus(request);
        } catch (Exception e) {
            throw new BaseException("查询物模型数据信息失败");
        }

        if (!response.body.success) {
            throw new BaseException("查询物模型数据信息失败");
        }

        return AjaxResult.success(response.body.data);
    }

    /**
     * 删除IOT平台产品数据
     *
     * @param request
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteIOTDevice(DeleteDeviceRequest request) {

        //先删数据库中的数据
        Device deviceIOT = deviceMapper.selectOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, request.getIotId()));
        deleteDeviceById(deviceIOT.getId());

        //删除IOT平台的产品数据
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());


        DeleteDeviceResponse response;

        try {
            response = client.deleteDevice(request);
        } catch (Exception e) {
            throw new RuntimeException("调用IOT平台删除设备失败");
        }


        if (!response.body.success) {

            throw new BaseException("调用IOT平台删除设备失败");
        }


    }
}
